package com.erp.erp_ui.Drawback.Service;

import com.erp.enums.ModuleTypeEnum;
import com.erp.erp_entitys.Cost.req.CostAnnexReq;
import com.erp.erp_entitys.Cost.vo.CostAnnexVO;
import com.erp.erp_entitys.Drawback.req.AddDrawbackReq;
import com.erp.erp_entitys.Drawback.vo.QueryDrawbackDetailVO;
import com.erp.erp_entitys.warehouse.entity.AnnexEntity;
import com.erp.erp_entitys.warehouse.entity.TempAnnexEntity;
import com.erp.erp_servers.Drawback.DrawbackService;
import com.erp.erp_servers.warehouse.IAnnexService;
import com.erp.erp_servers.warehouse.ITempAnnexService;
import com.erp.erp_ui.warehouse.enums.DataIsValidEnum;
import com.erp.erp_ui.warehouse.req.AnnexReq;
import com.erp.utils.DateUtils;
import com.erp.utils.R;
import com.erp.utils.ResultStatusEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zjk
 * @version 1.0
 * @description
 * @date 2021/1/15/015 0:47
 */
@Service
public class DrawbackAllService {
    /**
     * 日志
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(DrawbackAllService.class);

    private final DrawbackService drawbackService;
    /**
     * 附件接口
     */
    private final IAnnexService annexService;
    /**
     * 临时附件接口
     */
    private final ITempAnnexService tempAnnexService;

    public DrawbackAllService(DrawbackService drawbackService, IAnnexService annexService, ITempAnnexService tempAnnexService) {
        this.drawbackService = drawbackService;
        this.annexService = annexService;
        this.tempAnnexService = tempAnnexService;
    }

    /**
     * 登记退税信息，附件信息。
     * @param reqData
     * @return
     * @throws ParseException
     */
    @Transactional(rollbackFor = Exception.class)
    public R add(AddDrawbackReq reqData) throws ParseException {
        Integer num=drawbackService.updateDrawback(reqData);
        if (null==num){
            return R.build(ResultStatusEnum.SYSTEM_ERROR);
        }
        boolean flag = addAnnex(reqData.getAnnexList(), reqData.getDrawbackId(), reqData.getDrawbackOperatorName(), reqData.getDrawbackOperatorCode());
        if(!flag){
            LOGGER.info("仓库管理-其它出库-批量新增附件异常");
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
        //第三步：删除临时附件信息
        deleteTempAnnex(reqData.getAnnexList());

        return R.build(ResultStatusEnum.SUCCESS);
    }
    /**
     * 批量处理临时附件信息，将临时附件设置为失效
     * @param annexReqs
     */
    private void deleteTempAnnex(List<CostAnnexReq> annexReqs){
        //没有附件
        if(CollectionUtils.isEmpty(annexReqs)){
            return;
        }
        //存在附件
        for(CostAnnexReq annex : annexReqs){
            if(null != annex.getNews()){
                //旧附件,不用修改
                continue;
            }
            TempAnnexEntity tempAnnex = new TempAnnexEntity();
            //设置临时附件id
            tempAnnex.setId(annex.getId());
            //设置修改时间
            tempAnnex.setUpdateTime(new Date());
            //将附件设置为失效
            tempAnnex.setValid(0);
            tempAnnexService.update(tempAnnex);
        }

    }

    /**
     * 附件新增
     * @param annexReqs 附件信息
     * @param outStockId 退税id
     * @param operator 操作人
     * @param operatorNo 操作人编码
     * @return 是否新增成功(true:成功 false:失败 )
     */
    private boolean addAnnex(List<CostAnnexReq> annexReqs, Integer outStockId, String operator, String operatorNo) {
        try {
            //没有附件,不新增
            if(CollectionUtils.isEmpty(annexReqs)){
                return true;
            }
            //存在附件,新增附件信息
            List<AnnexEntity> list = new ArrayList<>();
            //获取旧的附件id集合
            List<Integer> oldIds = new ArrayList<>();
            for(CostAnnexReq annexReq : annexReqs){
                if(null != annexReq.getNews()){
                    //属于旧附件 只取id,不新增
                    oldIds.add(annexReq.getId());
                    continue;
                }
                AnnexEntity annex = new AnnexEntity();
                BeanUtils.copyProperties(annexReq, annex);
                //设置关联模块id
                annex.setModuleId(ModuleTypeEnum.MONEY_RECEIVE_DRAWBACK.getId());
                //设置关联模块父id
                annex.setParentId(outStockId);
                //设置上传时间
                annex.setUploadTime(DateUtils.convertStringToDate(annexReq.getUploadTime(), DateUtils.DATE_TIME_PATTERN));
                //设置修改时间
                annex.setUpdateTime(new Date());
                //设置操作人
                annex.setOperator(operator);
                //设置操作人编码
                annex.setOperatorNo(operatorNo);
                //设置数据有效
                annex.setValid(1);

                list.add(annex);
            }
            if(oldIds.size() > 0){
                //通过调拨id获取修改附件信息
                AnnexEntity annex = new AnnexEntity();
                annex.setModuleId(ModuleTypeEnum.MONEY_RECEIVE_DRAWBACK.getId());
                annex.setParentId(outStockId);
                //获取上次附件信息
                List<AnnexEntity> annexList = annexService.queryAll(annex);
                if(!CollectionUtils.isEmpty(annexList)){
                    //获取上次附件id集合
                    List<Integer> oldAnnexIds = annexList.stream().map(p -> p.getId()).collect(Collectors.toList());
                    //得到被删除的附件id
                    Collection collection = new ArrayList(oldAnnexIds);
                    collection.removeAll(oldIds);
                    if(collection.size() > 0){
                        Iterator<Integer> it = collection.iterator();
                        while (it.hasNext()){
                            int id = it.next();
                            AnnexEntity annexEntity = new AnnexEntity();
                            annexEntity.setId(id);
                            //将被删除的附件设为失效
                            annexEntity.setValid(DataIsValidEnum.INVALID.getId());

                            annexService.update(annexEntity);
                        }
                    }
                }
            }
            if(!CollectionUtils.isEmpty(list)){
                //附件批量新增
                int res = annexService.batchInsert(list);
                if(res == list.size()){
                    return true;
                }
            }
            return true;
        }catch (Exception e){
            throw new RuntimeException();
        }
    }

    /**
     * 获取退税详情，附件信息
     * @param drawbackId
     * @return
     */
    public QueryDrawbackDetailVO findDrawbackDetail(Integer drawbackId){
        //获取退税详情
        QueryDrawbackDetailVO detailVO= drawbackService.selectDrawbackDetailByDrawbackId(drawbackId);
        //获取附件详情
        AnnexEntity annexEntity = new AnnexEntity();
        annexEntity.setModuleId(ModuleTypeEnum.MONEY_RECEIVE_DRAWBACK.getId());
        annexEntity.setParentId(drawbackId);
        List<AnnexEntity> annexList = annexService.queryAll(annexEntity);

        List<CostAnnexVO> annexVos=new ArrayList<>();
        if (annexList.size()>0) {
            for (AnnexEntity annex : annexList) {
                CostAnnexVO annexVo = new CostAnnexVO();
                //赋值
                BeanUtils.copyProperties(annex, annexVo);
                //上传时间转换
                annexVo.setUploadTime(DateUtils.format(annex.getUploadTime(), DateUtils.DATE_TIME_PATTERN));
                //设置附件为旧附件,用以区分修改时附件状态
                annexVo.setNews(0);
                annexVos.add(annexVo);
            }
        }
        detailVO.setCostAnnexVOList(annexVos);
        return detailVO;
    }
}
